package com.hzjy.api.controller;

import com.alibaba.fastjson.JSON;
import com.hzjy.api.beans.HzjyDelist;
import com.hzjy.api.beans.HzjyProduct;
import com.hzjy.api.beans.HzjyProject;
import com.hzjy.api.mapper.ApiWorksMapper;
import com.hzjy.api.service.BqTokenService;
import com.hzjy.api.service.impl.ApiDelistServiceImpl;
import com.hzjy.api.service.impl.ApiProductServiceImpl;
import com.hzjy.api.service.impl.BqUserServiceImpl;
import com.hzjy.api.service.impl.HzjyAgreementServiceImpl;
import com.hzjy.api.vo.BqLoginUser;
import com.hzjy.api.vo.BqUser;
import com.hzjy.common.core.controller.ApiBaseController;
import com.hzjy.common.core.domain.AjaxResult;
import com.hzjy.common.enums.DelistingStatusEnum;
import com.hzjy.common.enums.TradingStatusEnum;
import com.hzjy.common.utils.JSONUtil;
import com.hzjy.common.utils.PageData;
import com.hzjy.common.utils.ServletUtils;
import com.hzjy.common.utils.StringUtils;
import com.hzjy.framework.config.ServerConfig;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.*;

/**
 * 我的摘牌
 *
 * @author
 */

@Api("我的摘牌页")
@RestController
@RequestMapping("/api/myDelisting")
public class ApiMyDelistingController extends ApiBaseController {
    private static final Logger log = LoggerFactory.getLogger(ApiMyDelistingController.class);
    @Autowired
    private BqTokenService bqTokenService;
    @Autowired
    private ApiDelistServiceImpl apiDelistServiceImpl;
    @Autowired
    private ApiProductServiceImpl apiProductService;
    @Autowired
    private HzjyAgreementServiceImpl hzjyAgreementService;
    @Autowired
    private BqUserServiceImpl bqUserService;

    @ApiOperation("获取我的摘牌各种状态数量")
    @PostMapping("/statusCount")
    public AjaxResult statusCount() {
        log.info("【获取用户摘牌各种状态数量】.");
        PageData pd = new PageData();
        BqLoginUser loginUser = bqTokenService.getBqLoginUser(ServletUtils.getRequest());
        if (loginUser == null) {
            return AjaxResult.error(401, "未登录");
        }
        BqUser bqUser = loginUser.getBqUser();
        Long userId = bqUser.getUserId();
        Map map = apiDelistServiceImpl.getDelistingStateNum(userId);
        return AjaxResult.success(200, "查询成功", map);
    }


    /**
     * 请求参数 当前页currentPage，status(多种用,隔开)   返回：当前页currentPage，总页数totalPage，总条数totalResult 数据
     *
     * @param pd
     * @return
     */
    @ApiOperation("我的摘牌作品和项目列表")
    @PostMapping("/list")
    public AjaxResult myDelistingList(@RequestBody PageData pd) {
        log.info("【我的摘牌作品和项目列表】.args:" + JSONUtil.map2json(pd));
        BqLoginUser loginUser = bqTokenService.getBqLoginUser(ServletUtils.getRequest());
        if (loginUser == null) {
            return AjaxResult.error(401, "未登录");
        }
        BqUser bqUser = loginUser.getBqUser();
        Long userId = bqUser.getUserId();
        Object currentPage = pd.get("currentPage");
        Object size = pd.get("size");
        if (currentPage == null) {
            return AjaxResult.error("参数错误");
        }
        Integer page = Integer.parseInt(currentPage.toString());
        if (page < 1) {
            pd.put("currentPage", 0);
        } else {
            pd.put("currentPage", (page - 1) * Integer.parseInt(size.toString()));
        }
        pd.put("size", size == null || pd.getInteger("size") < 1 ? 10 : pd.get("size"));
        pd.put("userId", userId);
        Integer status = Integer.parseInt(pd.get("status").toString());
        List<Integer> statusList = new ArrayList<>();
        if (status == -1) {
            //查询全部
            pd.remove("status");
        } else if (status == 1) {
            //待审核
            statusList.add(DelistingStatusEnum.Audit.getCode());
            statusList.add(DelistingStatusEnum.FirstTrial.getCode());
            //pd.put("status", DelistingStatusEnum.Audit.getCode() + "," + DelistingStatusEnum.FirstTrial.getCode());
        } else if (status == 2) {
            //摘牌成功--已成交
            statusList.add(DelistingStatusEnum.DelistSuccess.getCode());
            //pd.put("status", DelistingStatusEnum.DelistSuccess.getCode());
            statusList.add(DelistingStatusEnum.RecordImageSuccess.getCode());
        } else if (status == 3) {
            //待签订
            statusList.add(DelistingStatusEnum.TalkPrice.getCode());
            statusList.add(DelistingStatusEnum.Signing.getCode());
            statusList.add(DelistingStatusEnum.SignTimeOut.getCode());
//            pd.put("status", DelistingStatusEnum.TalkPrice.getCode() + "," +
//                    DelistingStatusEnum.Signing.getCode() + "," +
//                    DelistingStatusEnum.SignTimeOut.getCode());
        } else if (status == 4) {
            //交货中
            statusList.add(DelistingStatusEnum.PaySuccess.getCode());
            statusList.add(DelistingStatusEnum.ConfirmCollection.getCode());
            //pd.put("status", DelistingStatusEnum.PaySuccess.getCode() + "," + DelistingStatusEnum.ConfirmCollection.getCode());
        }
        pd.put("statusList",statusList);
        Map map = apiDelistServiceImpl.selectHzjyDelistList(pd);
        return AjaxResult.success("查询成功", map);
    }

    @ApiOperation("修改摘牌")
    @PostMapping("/edit")
    public AjaxResult editDelisting(@RequestBody HzjyDelist hzjyDelist) {
        log.info("【修改摘牌申请】.args:" + JSONUtil.object2json(hzjyDelist));
        BqLoginUser loginUser = bqTokenService.getBqLoginUser(ServletUtils.getRequest());
        if (loginUser == null) {
            return AjaxResult.error(401, "未登录");
        }
        HzjyDelist queryHzjyDelist = apiDelistServiceImpl.selectHzjyDelistById(hzjyDelist.getDelistId());
        if (queryHzjyDelist.getStatus() > DelistingStatusEnum.FinalTrial.getCode()) {
            return AjaxResult.error("当前摘牌申请状态不允许编辑.");
        }
        //待审核状态
        hzjyDelist.setStatus(DelistingStatusEnum.Audit.getCode());
        apiDelistServiceImpl.updateHzjyDelist(hzjyDelist);
        return AjaxResult.success("已提交审核，请耐心等待");
    }

    @ApiOperation("申请摘牌")
    @PostMapping("/applyDelisting")
    public AjaxResult applyDelisting(@RequestBody HzjyDelist hzjyDelist) {
        log.info("【申请摘牌】.args:" + JSONUtil.object2json(hzjyDelist));
        BqLoginUser loginUser = bqTokenService.getBqLoginUser(ServletUtils.getRequest());
        if (loginUser == null) {
            return AjaxResult.error(401, "未登录");
        }
        Long userId = loginUser.getBqUser().getUserId();
        HzjyProduct hzjyProduct = apiProductService.selectProductInfo(hzjyDelist.getProductId());
        log.info("【申请摘牌校验作品状态】:审批状态：" + hzjyProduct.getState() + ",上架状态:" + hzjyProduct.getUpState());
        if (hzjyProduct.getUpState() != null && hzjyProduct.getUpState() == 1
                && (hzjyProduct.getState() == TradingStatusEnum.TradingSuccess.getCode()
                || hzjyProduct.getState() == TradingStatusEnum.PartialCompleted.getCode())) {
            hzjyProduct.setState(TradingStatusEnum.PartialCompleted.getCode());
            //项目的时候
            if (hzjyProduct.getTradingType() == 1) {
                if (hzjyProduct.getState() != TradingStatusEnum.TradingSuccess.getCode() &&
                        hzjyProduct.getState() != TradingStatusEnum.PartialCompleted.getCode()) {
                    log.error("当前作品权利已经全部交易完成,无法申请摘牌");
                    return AjaxResult.error("当前作品权利已经全部交易完成,无法申请摘牌.");
                }
                //查询项目的挂牌权利
                HzjyProject queryProject = new HzjyProject();
                queryProject.setProductId(hzjyProduct.getProductId().toString());
                List<HzjyProject> projectList = apiProductService.queryProjectByProductId(queryProject);
                if (hzjyProduct.getTermType() == 0) {
                    //转让 无期限
                    log.info("转让无期限，可以摘牌.");

                } else if (hzjyProduct.getTermType() == 1) {
                    //许可  有期限
//                    if (!CollectionUtils.isEmpty(projectList)) {
//                        if (projectList.get(0).getPermissionEndTime() != null &&
//                                projectList.get(0).getPermissionEndTime().before(new Date())) {
//                            //已经过期
//                            log.error("许可已过期,无法摘牌");
//                            return AjaxResult.error("当前作品权利许可已过期,不允许摘牌.");
//                        } else {
//                            log.info("许可未过期，继续校验摘牌申请.");
//                        }
//                    }
                    if (projectList.get(0).getPermissionType() == 0) {
                        //专有许可 只能摘牌一次
                        //挂牌出售的权利
                        List<String> salePowerList = null;
                        if (!CollectionUtils.isEmpty(projectList)) {
                            String[] salePower = projectList.get(0).getTradingPower().split(",");
                            salePowerList = Arrays.asList(salePower);
                        }
                        List<String> pList = new ArrayList<String>(salePowerList);
                        HzjyDelist queryDelist = new HzjyDelist();
                        queryDelist.setProductId(hzjyProduct.getProductId());
                        //已经摘牌申请的产品
                        List<HzjyDelist> haveDelist = apiDelistServiceImpl.selectHzjyDelistList(queryDelist);
                        if (!CollectionUtils.isEmpty(haveDelist)) {
                            //已经有人摘牌当前许可
                            //判断当前摘牌的权利跟
                            for (HzjyDelist delist : haveDelist) {
                                String[] delistPower = delist.getDelistPower().split(",");
                                for (String power : delistPower) {
                                    if (salePowerList.contains(power)) {
                                        pList.remove(power);
                                    }
                                }
                            }
                        }
                        if (CollectionUtils.isEmpty(pList)) {
                            log.error("当前作品权利已经全部售出,不允许摘牌");
                            return AjaxResult.error("当前作品权利已经全部售出,不允许摘牌.");
                        } else {
                            //还有可售出权利
                            String[] delistPower = hzjyDelist.getDelistPower().split(",");
                            for (String power : delistPower) {
                                if (!pList.contains(power)) {
                                    log.error("当前作品权利部分已经售出,请重新选择摘牌权利.");
                                    return AjaxResult.error("当前作品权利部分已经售出,请重新选择摘牌权利\".");
                                }
                            }
                            if (pList.size() == delistPower.length) {
                                log.info("此次摘牌申请将权利全部购买完成");
                                hzjyProduct.setState(TradingStatusEnum.Finished.getCode());
                            }
                            log.info("作品专有许可权利校验完成,允许摘牌.");
                        }
                    } else if (projectList.get(0).getPermissionType() == 1) {
                        //非专有许可 可以摘牌很多次
                        log.info("作品非专有许可权利校验完成,允许摘牌.");
                    }
                }

            }
            apiProductService.updateHzjyProduct(hzjyProduct);
            //待审核状态
            hzjyDelist.setStatus(DelistingStatusEnum.Audit.getCode());
            hzjyDelist.setCreateTime(new Date());
            hzjyDelist.setUserId(userId.toString());
            log.info("------------------hzjyDelist--------------"+ hzjyDelist.toString());
            apiDelistServiceImpl.insertHzjyDelist(hzjyDelist);
            return AjaxResult.success("已提交审核，请耐心等待");
        } else {
            log.error("当前作品状态异常,不允许摘牌.");
            return AjaxResult.error("当前作品状态异常,不允许摘牌.");
        }
    }

    @ApiOperation("查看摘牌信息")
    @PostMapping("/info")
    public AjaxResult getInfo(@RequestBody PageData pd) {
        BqLoginUser loginUser = bqTokenService.getBqLoginUser(ServletUtils.getRequest());
        if (loginUser == null) {
            return AjaxResult.error(401, "未登录");
        }
        Object delistId = pd.get("delistId");
        if (delistId != null) {
            HzjyDelist hzjyDelist = apiDelistServiceImpl.selectHzjyDelistById(Long.valueOf(delistId.toString()));
            log.info("【查看摘牌信息,查询摘牌申请信息】：" + JSONUtil.object2json(hzjyDelist));
            if (hzjyDelist != null) {
                return AjaxResult.success("查询成功", hzjyDelist);
            } else {
                return AjaxResult.error("未查到对应作品摘牌申请.");
            }
        } else {
            return AjaxResult.error(500, "参数为空");
        }
    }

    @ApiOperation("去签订摘牌方与挂牌方协议")
    @PostMapping("/getDelistingContract")
    public AjaxResult getDelistingContract(@RequestBody PageData pd) {
        BqLoginUser loginUser = bqTokenService.getBqLoginUser(ServletUtils.getRequest());
        if (loginUser == null) {
            return AjaxResult.error(401, "未登录");
        }
        Long userId = loginUser.getBqUser().getUserId();
        BqUser byUserId = bqUserService.findByUserId(userId.toString());
        if (byUserId.getRealNameCertification().equals(2)){
            return AjaxResult.error(500, "请先进行实名认证");
        }
        Object delistId = pd.get("delistId");
        Integer code = apiProductService.createDelistingContract(Long.valueOf(delistId.toString()), userId.toString());
        if (code == 1) {
            return AjaxResult.success("摘牌协议签订完成.");
        } else {
            return AjaxResult.success("摘牌协议签订失败");
        }
    }

    @ApiOperation("去签订摘牌方与平台方协议")
    @PostMapping("/getTradeAndDelistingContract")
    public AjaxResult getTradeAndDelistingContract(@RequestBody PageData pd) {
        BqLoginUser loginUser = bqTokenService.getBqLoginUser(ServletUtils.getRequest());
        if (loginUser == null) {
            return AjaxResult.error(401, "未登录");
        }
        Long userId = loginUser.getBqUser().getUserId();
        BqUser byUserId = bqUserService.findByUserId(userId.toString());
        if (byUserId.getRealNameCertification().equals(2)){
            return AjaxResult.error(500, "请先进行实名认证");
        }
        Object delistId = pd.get("delistId");
        Integer code = apiProductService.createDelisContract(Long.valueOf(delistId.toString()), userId.toString());
        if (code == 1) {
            return AjaxResult.success("摘牌协议签订完成,请继续完成支付.");
        } else {
            return AjaxResult.success("摘牌协议签订失败");
        }
    }


    @ApiOperation("摘牌提交审核")
    @PostMapping("/submitApprove")
    public AjaxResult submitApprove(@RequestBody PageData pd) {
        BqLoginUser loginUser = bqTokenService.getBqLoginUser(ServletUtils.getRequest());
        if (loginUser == null) {
            return AjaxResult.error(401, "未登录");
        }
        Object delistId = pd.get("delistId");
        if (delistId != null) {
            HzjyDelist hzjyDelist = apiDelistServiceImpl.selectHzjyDelistById(Long.valueOf(delistId.toString()));
            if (hzjyDelist.getStatus() == DelistingStatusEnum.Reject.getCode() ||
                    hzjyDelist.getStatus() == DelistingStatusEnum.FirstTrial.getCode()) {
                hzjyDelist.setStatus(DelistingStatusEnum.Audit.getCode());
                apiDelistServiceImpl.updateHzjyDelist(hzjyDelist);
                return AjaxResult.success("摘牌提交审核成功");
            } else {
                return AjaxResult.error("摘牌提交审核失败,当前状态不能提交审核.");
            }
        } else {
            return AjaxResult.error(500, "参数为空");
        }
    }

    @ApiOperation("查询挂牌出售权力")
    @PostMapping("/findTradingPower")
    public AjaxResult findTradingPower(@RequestBody HzjyProduct hzjyProduct){
        HzjyProduct newHzjyProduct = apiProductService.findTradingPower(hzjyProduct);
        return AjaxResult.success(200,"成功",newHzjyProduct);
    }
}
